<template>
  <el-form ref="form" label-width="80px" size="small">
    <el-form-item label="模式">
      <el-select v-model="mode" placeholder="请选择">
        <el-option
          v-for="item in modeOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
    </el-form-item>
    <div style="padding-bottom:16px;text-align:right">
      <el-button @click="measure" size="small" type="primary">测量</el-button>
      <el-button @click="clearLayers" size="small">清除</el-button>
    </div>
  </el-form>
</template>

<script>
import * as Ces from 'cesium'
import '@/components/dogeo/cesium/extends/cesium-ext.min.js'
const Cesium = Ces

export default {
  name: 'tool-measure-distance',

  props: {
    viewer: {
      type: Object,
      default () {
        return null
      }
    }
  },

  data () {
    return {
      modeOptions: [
        {label: '空间测距', value: 1},
        {label: '贴地测距', value: 2}
      ],
      mode: 1
    }
  },

  watch: {
    mode () {
      this.handleChangeMode(this.mode)
    }
  },

  mounted () {
    this.init()
  },

  methods: {
    // 初始化测量器
    init () {
      if (!this.viewer) {
        return true
      }
      if (!this.areaWidget) {
        this.areaWidget = this.addWidget(1)
      }
      if (!this.groundWidget) {
        this.groundWidget = this.addWidget(2)
      }
    },
    // 实例化插件
    addWidget (mode) {
      var color = mode == 1 ? Cesium.Color.CHARTREUSE : Cesium.Color.CYAN
      return new Cesium.MeasureDistanceWidget({
        viewer: this.viewer,
        color: color,
        lineWidth: 3.0,
        mode: mode,
        labelGraphics: {
          showBackground: true,
          fillColor: Cesium.Color.WHITE.withAlpha(1),
          backgroundColor: Cesium.Color.BLACK.withAlpha(0.8)
        }
      })
    },
    // 插件检查
    checkWidget () {
      if (this.areaWidget.handler || this.groundWidget.handler) {
        this.$message.error('请完成当前操作后再开启')
        return false
      }
      return true
    },
    handleChangeMode () {
      if (this.mode === 1 && this.groundWidget.handler) {
        this.mode = 2
        this.$message.error('请完成当前操作后再开启')
      } else if (this.mode === 2 && this.areaWidget.handler) {
        this.mode = 1
        this.$message.error('请完成当前操作后再开启')
      }
    },
    // 测量
    measure () {
      if (!this.checkWidget()) {
        return true
      }
      // 贴地测距(单位：千米)
      if (this.mode === 2) {
        this.groundWidget.activate()
      }
      // 空间测距(单位：千米)
      else {
        this.areaWidget.activate()
      }
    },
    // 清除图层
    clearLayers () {
      this.areaWidget.clear()
      this.groundWidget.clear()
    }
  }
}
</script>